import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols, limit, sin, exp, log

# 定义符号变量
x = symbols('x')

# 定义两个函数
f = x**2 + 2*x  # lim(x->1) f(x) = 3
g = x**3 - x    # lim(x->1) g(x) = 0

# 计算各个极限
lim_f = limit(f, x, 1)
lim_g = limit(g, x, 1)
lim_sum = limit(f + g, x, 1)
lim_product = limit(f * g, x, 1)

print(f"lim(x->1) f(x) = {lim_f}")
print(f"lim(x->1) g(x) = {lim_g}")
print(f"lim(x->1)[f(x) + g(x)] = {lim_sum}")
print(f"lim(x->1)[f(x) * g(x)] = {lim_product}")
print(f"验证加法法则: {lim_f} + {lim_g} = {lim_f + lim_g}, 实际极限: {lim_sum}")
print(f"验证乘法法则: {lim_f} * {lim_g} = {lim_f * lim_g}, 实际极限: {lim_product}")

# 可视化
x_vals = np.linspace(0.5, 1.5, 100)
f_vals = x_vals**2 + 2*x_vals
g_vals = x_vals**3 - x_vals
sum_vals = f_vals + g_vals
product_vals = f_vals * g_vals

plt.figure(figsize=(12, 8))

plt.subplot(2, 2, 1)
plt.plot(x_vals, f_vals, 'b-', label=r'$f(x) = x^2 + 2x$', linewidth=2)
plt.axvline(x=1, color='r', linestyle='--', alpha=0.7)
plt.axhline(y=lim_f, color='r', linestyle='--', alpha=0.7)
plt.title(f'lim f(x) = {lim_f} (x→1)')
plt.legend()
plt.grid(True, alpha=0.3)

plt.subplot(2, 2, 2)
plt.plot(x_vals, g_vals, 'g-', label=r'$g(x) = x^3 - x$', linewidth=2)
plt.axvline(x=1, color='r', linestyle='--', alpha=0.7)
plt.axhline(y=lim_g, color='r', linestyle='--', alpha=0.7)
plt.title(f'lim g(x) = {lim_g} (x→1)')
plt.legend()
plt.grid(True, alpha=0.3)

plt.subplot(2, 2, 3)
plt.plot(x_vals, sum_vals, 'm-', label=r'$f(x) + g(x)$', linewidth=2)
plt.axvline(x=1, color='r', linestyle='--', alpha=0.7)
plt.axhline(y=lim_sum, color='r', linestyle='--', alpha=0.7)
plt.title(f'lim [f(x) + g(x)] = {lim_sum} (x→1)')
plt.legend()
plt.grid(True, alpha=0.3)

plt.subplot(2, 2, 4)
plt.plot(x_vals, product_vals, 'c-', label=r'$f(x) \cdot g(x)$', linewidth=2)
plt.axvline(x=1, color='r', linestyle='--', alpha=0.7)
plt.axhline(y=lim_product, color='r', linestyle='--', alpha=0.7)
plt.title(f'lim [f(x) · g(x)] = {lim_product} (x→1)')
plt.legend()
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

